import java.io.*;
import java.util.regex.Pattern;
import java.util.HashSet;
import java.util.Collection;

/**
 * example run to grab all java classes is 
 * java FileLister src .*\.java$ relative java_src_list.txt
 */
public class FileLister {

    public static void main(String[] args) throws Exception {
        String srcDirName = args[0];
        File srcDir = new File(srcDirName);

        Collection<File> files = new HashSet();
        listFiles(srcDir, new PatternRecursiveFilter(args[1]), files);

        String outName = "";
        boolean relative = false;
        int i = 2;
        while(i < args.length && (!relative || outName.length() == 0)) {
            if("relative".equals(args[i])) {
                relative = true;
            }
            else {
                outName = args[i];
            }
            i++;
        }
        PrintStream out = outName.length() > 0 ? new PrintStream(new File(outName)) : System.out;
        String separator = outName.length() > 0 ? " " : "\n";

        for(File foundFile : files) {
            String fileName = foundFile.getCanonicalPath();
            if(relative) {
                fileName = fileName.substring(fileName.indexOf(srcDirName));
            }
            out.print(fileName);
            out.print(separator);
        }
        out.flush();
        out.close();
    }

    static void listFiles(File dir, FileFilter filter, Collection<File> collection) {
        for(File file : dir.listFiles(filter)) {
            if(file.isDirectory()) {
                listFiles(file, filter, collection);
            }
            else {
                collection.add(file);
            }
        }
    }

    static void outputList(Collection<String> list, String separator, PrintStream out) {

    }

    static class PatternRecursiveFilter implements FileFilter {
        private Pattern pattern;

        public PatternRecursiveFilter(String pattern) {
            this.pattern = Pattern.compile(pattern);
        }

        public boolean accept(File file) {
            try {
                return file.isDirectory() || pattern.matcher(file.getCanonicalPath()).matches();
            }
            catch(IOException e) {
                System.err.println(e.getMessage());
            }
            return false;
        }
    }
}